<template>
  <div id="flybean_list">
    <div class="search-box">
      <Row type="flex" justify="space-between">
        <Row type="flex" align='middle'>
          <Col class="search-item"><span class="search-label">活动名称：</span><Input placeholder="请输入" v-model='activityName' :maxlength="20" @on-keyup='filterName' @on-blur="filterName"></Input></Col>
          <Col class="search-item">
            <span class="search-label">活动状态：</span>
            <Select v-model="searchObj.status" @on-change="search"
              style="width:180px">
              <Option :value="-1">全部</Option>
              <Option v-for="item in statusList" :value="item.value" :key="item.value">{{ item.label }}</Option>
            </Select>
          </Col>
          <Col class='treeselect_box'>
            <span class="search-label">门店：</span>
            <treeselect class="list_treeselect" placeholder="请选择"
              :options="options" style="width:210px;"
              v-model='searchObj.shopValue' multiple value-consists-of="LEAF_PRIORITY"
              :normalizer="normalizer" :limitText='limitText' :limit='1'
              @input='search'
              />
          </Col>
          <Col class="search-item">
          <Button class="search-btn"
                  type='primary'
                  @click="doSearch"
                  >查询</Button>
          </Col>
          <Col class="search-item">
          <Button class="search-btn"
                @click="doReset">重置</Button>
          </Col>
        </Row>
        <Row type="flex" justify="end">
        <Col class="search-item" style="padding-right:15px;">
            <Button class="search-btn" type="primary" @click="skipAdd" v-if="hasPermission('moms:market:ticketactivitycreate')">创建
            </Button>
        </Col>
      </Row>
      </Row>
    </div>
    <Table stripe class="table-list" :columns="columns" :data="tableData" :loading="loading" :height="tableHeight">
      <template slot-scope="{ row }" slot="activityStatus">
        <span>{{row.activityStatus == 0 ? '未开始' : row.activityStatus == 1 ? '进行中' : row.activityStatus == 2 ? '已结束' : ''}}</span>
      </template>
      <template slot-scope="{ row }" slot="action">
        <i class="iconsys icondetail" title="查看" @click='skipDetail(row)'></i>
        <i class="iconsys iconedit" title="编辑" @click='skipEdit(row)' v-if="row.activityStatus === 0"></i>
        <Poptip confirm title="确认删除此数据吗？" transfer @on-ok="sureDel(row)" style="text-align:left" v-if="row.activityStatus === 0">
          <i class="iconsys icondel" title="删除"></i>
        </Poptip>
        <Poptip confirm title="确认结束此活动吗？" transfer style="text-align:left" @on-ok="skipOver(row)" v-if="row.activityStatus === 1">
            <i class="iconsys iconxiajia" title="立即结束"></i>
          </Poptip>
      </template>
    </Table>
    <Row type='flex' justify="end" style='padding: 20px'>
      <Col>
        <Page :total="pageObj.total"
              :page-size='pageObj.pageSize'
              :current='pageObj.pageIndex'
              show-total
              show-sizer
              @on-change='changePageIndex'
              @on-page-size-change='changePageSize' />
      </Col>
    </Row>
  </div>
</template>

<script>
import { getFlyBeanList, delFlyBean, endFlyBean } from '@/api/market/flybean.js'
import enumsMixin from '../enums.js'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { getEmployeeTree } from '@/api/system/employee.js'
export default {
  name: 'flybean_list',
  mixins: [enumsMixin],
  components: { Treeselect },
  computed: {
    tableHeight () {
      let height = this.tableData.length > 10 ? 520 : 0
      return height
    }
  },
  watch: {
    '$route' (newRoute) {
      if (newRoute.name === 'flybean_list') {
        this.getData()
      }
    }
  },
  data () {
    return {
      options: [],
      normalizer (node) {
        if (node.childList) {
          if (node.childList.length > 0) {
            return {
              id: node.id,
              label: node.orgName,
              children: node.childList
            }
          } else {
            return {
              id: node.id,
              label: node.orgName
            }
          }
        }
      },
      activityName: '',
      loading: false,
      tableData: [],
      columns: [
        {
          title: '活动编号',
          key: 'activityCode',
          fixed: 'left',
          width: 130
        },
        {
          title: '活动名称',
          key: 'activityName'
        },
        {
          title: '活动开始时间',
          key: 'activityStart'
        },
        {
          title: '活动结束时间',
          key: 'activityEnd'
        },
        {
          title: '活动状态',
          slot: 'activityStatus'
        },
        {
          title: '创建人',
          key: 'creatorName'
        },
        {
          title: '创建时间',
          key: 'createTime'
        }
      ],
      searchObj: {
        shopValue: [],
        activityName: '',
        status: -1
      },
      pageObj: {
        total: 0,
        pageIndex: 1,
        pageSize: 10
      }
    }
  },
  methods: {
    limitText () {
      return '...'
    },
    getOrgTree () { // 获取组织机构树
      getEmployeeTree({
        'merchantId': this.$store.state.user.merchantId,
        'status': 1,
        'orgType': 1
      }).then((res) => {
        if (res.data.status === 200) {
          this.options.push(res.data.data)
          this.getStore([res.data.data])
          this.getData()
        } else {
          this.$Message.error(res.data.error)
        }
      })
    },
    // 递归取门店
    getStore (list) {
      list.forEach(ele => {
        if (ele.childList.length > 0) {
          this.getStore(ele.childList)
        } else {
          if (ele.orgType === 1) {
            this.searchObj.shopValue.push(ele.id)
          }
        }
      })
    },
    filterName () {
      this.activityName = this.activityName.replace(/[^0-9A-Za-z\u4e00-\u9fa5]/, '')
    },
    search () {
      this.pageObj.pageIndex = 1
      this.getData()
    },
    doSearch () {
      this.pageObj.pageIndex = 1
      this.searchObj.activityName = this.activityName
      this.getData()
    },
    doReset () {
      this.activityName = ''
      this.searchObj = {
        shopValue: [],
        activityName: '',
        status: -1
      }
      this.pageObj = {
        total: 0,
        pageIndex: 1,
        pageSize: 10
      }
      this.options = []
      this.getOrgTree()
      this.getData()
    },
    changePageIndex (index) {
      this.pageObj.pageIndex = index
      this.getData()
    },
    changePageSize (size) {
      this.pageObj.pageSize = size
      this.pageObj.pageIndex = 1
      this.getData()
    },
    skipAdd () {
      this.$router.push({ name: 'flybean_create' })
    },
    skipDetail (row) {
      this.$router.push({ name: 'flybean_detail', params: { id: row.id } })
    },
    skipEdit (row) {
      this.$router.push({ name: 'flybean_edit', params: { id: row.id } })
    },
    skipOver (row) {
      endFlyBean({ id: row.id }).then(res => {
        if (res.data.status === 200) {
          this.$Message.success('立即结束成功！')
          this.getData()
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
    },
    sureDel (row) {
      delFlyBean({ id: row.id }).then(res => {
        if (res.data.status === 200) {
          this.$Message.success('删除成功！')
          this.getData()
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
    },
    getData () {
      this.loading = true
      getFlyBeanList({
        merchantId: this.$store.state.user.merchantId,
        activityName: this.searchObj.activityName,
        activityStatus: this.searchObj.status === -1 ? '' : this.searchObj.status,
        shopIds: this.searchObj.shopValue,
        offset: this.pageObj.pageSize * (this.pageObj.pageIndex - 1),
        limit: this.pageObj.pageSize
      }).then(res => {
        this.loading = false
        const result = res.data || {}
        if (result.status === 200) {
          this.tableData = result.data || []
          this.pageObj.total = result.totalCount
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.loading = false
        this.$Message.error(`${err}`)
      })
    }
  },
  mounted () {
    this.getOrgTree()
    if (this.hasPermission(['moms:market:ticketactivitydetail', 'moms:market:ticketactivityupdate', 'moms:market:ticketactivitydelete', 'moms:market:ticketactivityclose'])) {
      this.columns.push({
        title: '操作',
        slot: 'action',
        fixed: 'right',
        width: 180
      })
    }
  }
}
</script>

<style lang="less">
#flybean_list{
  .treeselect_box {
    display: flex;
    align-items: center;
    margin-left: 30px;
    padding-top: 24px;
    span {
      line-height: 20px;
      margin-right: 8px;
    }
  }
  .vue-treeselect__control,
  .vue-treeselect__input-container {
    height: 32px !important;
  }
}
</style>
